package com.mairuide.phone.trackevents;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.mairuide.bill.utils.DateUtils;
import com.mairuide.bill.utils.ExcelUtils;
import com.mairuide.phone.abnormalphone.AbnormalPhoneParams;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.base.PageSupport;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.bill.utils.ExcelUtil;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;
import com.mairuide.httpclient.BaseSite;
import com.mairuide.phone.PhoneRecord;
import com.mairuide.phone.callanalysis.entity.PhoneMapDetail;
/**
 * 活动轨迹
 * @author mh
 *
 */
@Controller
@RequestMapping("/track")
public class TrackEventsController extends BaseController {
	@Resource
	private TrackEventsService trackEventsService;
	
	@Resource
	private DataOperationLogService dataOperationLogService;
	
    @Resource
    private BaseSite baseSite;

	/**
	 * 活动轨迹入口
	 * @param model
	 * @param pagesupport
	 * @return
	 */
	@ModuleCode(pValue = "callanalysis", value = "teMC")
	@RequestMapping(value = "/trackEventsInit", method = RequestMethod.GET)
	public Object trackEventsInit(ModelMap model, PageSupport pagesupport) {
		return "/phone/interactivetrajectory/trackevents";
	}

	/**
	 * 活动轨迹分析
	 * @param model
	 * @param eocap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/trackEvents", method = RequestMethod.POST)
	public Object importFile(ModelMap model,TrackEventsParams tep) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(tep.getShowType()) && tep.getShowType().equals("0")) {
			List<TrackEvents> ecas = trackEventsService.findTrackEvents(tep);
			if(null != ecas && ecas.size() > 0) {
				result.put("total", ecas.size());
				result.put("rows", ecas);
			}else {
				result.put("total", 0);
				result.put("rows", new ArrayList<>());
			}
		}else {
			Map<String, String> trackEventsMap = trackEventsService.findTrackEventsMap(tep);
			result.put("total", 0);
			result.put("rows", new ArrayList<>());
			result.put("map",trackEventsMap);
		}
		return result;
	}
	
	/**
	 * 通话详情跳转
	 * @param model
	 * @param eocap
	 * @return
	 */
	@RequestMapping(value = "/trackDetailsGO", method = RequestMethod.GET)
	public Object trackDetailsGO(ModelMap model, TrackEventsParams tep) {
		model.addAttribute("serviceNumber", tep.getServiceNumber());
		model.addAttribute("caseId", tep.getCaseId());
		return "/phone/interactivetrajectory/trackDetails";
	}
	
	/**
	 * 活动轨迹-通话详情
	 * @param model
	 * @param eocap
	 * @return
	 */
	@RequestMapping(value = "/trackDetails", method = RequestMethod.POST)
	@ResponseBody
	public Object eachOtherDetails(ModelMap model,TrackEventsParams eocap, Integer page,Integer rows,String sort, String order) {
		eocap.setCheckedPhone("");
		Page<PhoneRecord> pagePh = trackEventsService.trackDetails(eocap, new PageRequest(page-1, rows), sort, order);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", pagePh.getTotalElements());

		result.put("rows", pagePh.getContent());
		return result;
	}

	@RequestMapping(method= RequestMethod.POST,value = "/trackDetailsExcel")
	@ResponseBody
	public void findDealFlowListExcel(@RequestBody TrackEventsParams eocap, String sort, String order, HttpServletResponse response )throws Exception{
		XSSFWorkbook workbook1 = new XSSFWorkbook();
		SXSSFWorkbook wb = new SXSSFWorkbook(workbook1, 100);
		//创建HSSFWorkbook对象(excel的文档对象)
		//建立新的sheet对象（excel的表单）
		Sheet sheet=wb.createSheet("通话详情");
		//在sheet里创建第二行
		Row row2=sheet.createRow(0);
		//创建单元格并设置单元格内容
		row2.createCell(0).setCellValue("机主号码");
		row2.createCell(1).setCellValue("呼叫类型");
		row2.createCell(2).setCellValue("对方号码");
		row2.createCell(3).setCellValue("通话日期");
		row2.createCell(4).setCellValue("通话时长");
		row2.createCell(5).setCellValue("基站号(CI)");
		row2.createCell(6).setCellValue("小区号(LAC)");
		row2.createCell(7).setCellValue("地址");
		//在sheet里创建第三行
		Page<PhoneRecord> pagePh = trackEventsService.trackDetails(eocap, new PageRequest(0, Integer.MAX_VALUE), sort, order);
		List<PhoneRecord> content = pagePh.getContent();
		if (content!=null && content.size()>0){
			for (int i=0;i<content.size();i++){
				PhoneRecord map = content.get(i);
				Row row3=sheet.createRow(i+1);
				row3.createCell(0).setCellValue(map.getServiceNumber());
				row3.createCell(1).setCellValue(map.getCallType()==0?"主叫":"被叫");
				row3.createCell(2).setCellValue(map.getPartyNumber());
				row3.createCell(3).setCellValue(DateUtils.getDateString(map.getStartingTime()));
				row3.createCell(4).setCellValue(map.getTalkTime());
				row3.createCell(5).setCellValue(map.getCid());
				row3.createCell(6).setCellValue( map.getLac());
				row3.createCell(7).setCellValue(map.getAddress());
			}
		}
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String fileName = "通话详情" + dateFormat.format(new Date());
		//输出Excel文件
		OutputStream output=response.getOutputStream();
		response.reset();
		response.setHeader("Content-disposition", "attachment; filename="+ ExcelUtils.toUtf8String(fileName+".xlsx"));
		response.setContentType("application/msexcel");
		wb.write(output);
		output.close();
		//添加导出日志
		dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.PHONERECORDEXPORT, ActionType.EXPORT);

	}

//	
	/**
     * 活动轨迹导出excel
	 * @throws Exception 
     */
    @RequestMapping("/exportTrackEvents")
    @ResponseBody
    public void exportTrackEvents(HttpServletResponse response, TrackEventsParams tep) throws Exception {
        // 生成导出excel名称
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "活动轨迹" + dateFormat.format(date);
	    // 设置导出Excel标题
		String[] titles = { "开始日期", "结束日期", "通话次数", "基站数量"};
        List<TrackEvents> ecas = trackEventsService.findTrackEvents(tep);
        List<Map<Integer, String>> lists = new ArrayList<Map<Integer, String>>();
		if (null != ecas && !ecas.isEmpty()) {
			for (TrackEvents eca : ecas) {
				Map<Integer, String> map = new HashMap<Integer, String>();
				map.put(0, eca.getStartTime() == null ? "" : eca.getStartTime());
				map.put(1, eca.getEndTime() == null ? "" : eca.getEndTime());
				map.put(2, eca.getCallNum() == null ? "" : eca.getCallNum().toString());
				map.put(3, eca.getStationNum() == null ? "" : eca.getStationNum().toString());
				lists.add(map);
			}
		}

		// 插入导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.TRACKEVENTS, ActionType.EXPORT);
		// 把导出的内容写入到流里面
		byte[] content = ExcelUtil.writeExcel(titles, lists);
		InputStream is = new ByteArrayInputStream(content);

		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
		}
	}
}
